//
//  CityListViewController.m
//  BaseTools
//
//  Created by 李挺哲 on 15/8/14.
//  Copyright (c) 2015年 ltz. All rights reserved.
//
#import <CoreLocation/CoreLocation.h>
#import "CityListViewController.h"
#import "City.h"
#import "ChineseString.h"
#import "LocationTableViewCell.h"
#import "HotCityCell.h"
#import "RecentVisitedCityCell.h"

@interface CityListViewController ()<CLLocationManagerDelegate>
{LocationTableViewCell *locationCityCell;
}
@property (strong, nonatomic) CLLocationManager* locationManager;
@property(strong,nonatomic)NSString *cityName;
@property(strong,nonatomic)NSArray *orignArray;
@property(strong,nonatomic)NSMutableArray * mutableArray;
//首字母
@property(nonatomic,retain)NSMutableArray *indexArray;
//分类结果
@property(nonatomic,retain)NSMutableArray *ResultArray;


@end
@implementation CityListViewController
-(void)viewDidLoad{
    [super  viewDidLoad];
    [self initNavigationTitle:@"城市列表" barTintColor:0x1E86CB titleColor:0xFFFFFF isTranslucent:NO isHidden:NO];
    [self showNavigationLeftButtonTitle:@"返回" tintColor:0xFFFFFF];
    
    [self startLocation];
    
    //    UISearchBar *bar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
    //    bar.placeholder=@"输入城市名称";
    //    [_tableView setTableHeaderView:bar];
    
    NSBundle *bundle = [NSBundle mainBundle];
    // 加载数据
    self.orignArray = [NSArray arrayWithContentsOfFile:[bundle pathForResource:@"citysArray" ofType:@"plist"]];
    _mutableArray=[NSMutableArray array];
    for (NSDictionary * dict in _orignArray) {
        City *c=[[City alloc] initWithDict:dict];
        [_mutableArray addObject:c];
        
    }
    //分类
    
    self.indexArray = [ChineseString cityIndexArray:_mutableArray];
    [self.indexArray insertObject:@"定位" atIndex:0];
    [self.indexArray insertObject:@"最近" atIndex:1];
    [self.indexArray insertObject:@"热门" atIndex:2];
    
    self.ResultArray = [ChineseString SortCityArray:_mutableArray];
    
}
-(void)startLocation{
    
    self.locationManager=[[CLLocationManager alloc] init];
    _locationManager.delegate=self;
    _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    _locationManager.distanceFilter=kCLDistanceFilterNone;
    //    2. 调用请求：
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 8.0)
    {
        //设置定位权限 仅ios8有意义
        
        [_locationManager requestAlwaysAuthorization];// 前后台同时定位
    }
    [_locationManager startUpdatingLocation];
    
    ;
}
#pragma mark -Section的Header的值
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    
    NSString *key = [_indexArray objectAtIndex:section];
    return key;
    
    
}
#pragma mark - Section header view
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0)];
    view.backgroundColor=kUIColorFromRGB(0x1E86CB) ;
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 22)];
    lab.backgroundColor =kUIColorFromRGB(0x1E86CB) ;
    lab.text = [_indexArray objectAtIndex:section];
    lab.textColor = [UIColor whiteColor];
    lab.textAlignment=NSTextAlignmentCenter;
    [view addSubview:lab];
    return view;
}
#pragma mark - row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if(indexPath.section==0){
        return 50.0;
    }
    
    else if (indexPath.section==1){
        
        return 50.0;
    }
    else if(indexPath.section==2){
        return  200.0;
    }
    else{
        return 44.0;
    }
    
}

#pragma mark -
#pragma mark Table View Data Source Methods
#pragma mark -设置右方表格的索引数组
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return _indexArray;
}

#pragma mark -
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return index;
}

#pragma mark -允许数据源告知必须加载到Table View中的表的Section数。
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_indexArray count];
}
#pragma mark -设置表格的行数为数组的元素个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section==0){
        return 1;
    }
    else if(section==1){
        return 1;
    }
    else if(section==2){
        return 1;
    }
    else{
        return [[self.ResultArray objectAtIndex:section-3] count];
    }
    
}
#pragma mark -每一行的内容为数组相应索引的值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    if (indexPath.section==0) {
        
        locationCityCell=  [LocationTableViewCell locationCellWithTableView:tableView];
        
        
        return locationCityCell;
        
    }
    else if (indexPath.section==1){
        
        RecentVisitedCityCell *cell=[RecentVisitedCityCell RecentVisitedCityCellWithTableView:tableView];
        return cell;
        
    }
    else if (indexPath.section==2){
        HotCityCell *cell=[HotCityCell HotCityCellWithTableView:tableView];
        
        return cell;
    }
    else{
        UITableViewCell * cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        City *c= [[self.ResultArray objectAtIndex:indexPath.section-3]objectAtIndex:indexPath.row];
        cell.backgroundColor=kUIColorFromRGB(0XECECEC);
        cell.textLabel.text = c.name;
        return cell;
        
        
    }
}
#pragma mark - Select内容为数组相应索引的值
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section==0) {
        return;
    }
    
    else{
        NSLog(@"---->%@",[[self.ResultArray objectAtIndex:indexPath.section]objectAtIndex:indexPath.row]);
        City *c= [[self.ResultArray objectAtIndex:indexPath.section-3]objectAtIndex:indexPath.row];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:c.name
                                                       delegate:nil
                                              cancelButtonTitle:@"YES" otherButtonTitles:nil];
        [alert show];
        
    }
}



-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    
    [_locationManager stopUpdatingLocation];
    NSLog(@"location ok");
    
    NSLog(@"%@",[NSString stringWithFormat:@"经度:%3.5f\n纬度:%3.5f",newLocation.coordinate.latitude,newLocation.coordinate.longitude]);
    
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        //        NSLog(@"%@",cl);
        
        CLPlacemark * placemark=placemarks[0];
        
        
        NSLog(@"%@",placemark.locality);
        //        NSLog(@"%@",placemark);
        
    }];
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *cl = [locations objectAtIndex:0];
    
    
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:cl completionHandler:^(NSArray *placemarks, NSError *error) {
        //        NSLog(@"%@",cl);
        CLPlacemark * placemark=placemarks[0];
        //获取城市
        
        NSString *city = placemark.locality;
        
        if (!city) {
            //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
            city = placemark.administrativeArea;
        }
        self.cityName = city;
        locationCityCell.locationingBut.hidden=YES;
        locationCityCell.locationCityBut.hidden=NO  ;
        [locationCityCell.locationCityBut setTitle:_cityName forState:UIControlStateNormal];
    }];
    
    [_locationManager stopUpdatingLocation];
    
    
}


//获取定位失败回调方法
#pragma mark - location Delegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"Location error!");
    
    
}

@end
